package io.github.lee.jel.repository

import io.github.lee.jel.api.ApiModule
import io.github.lee.jel.domain.Item
import io.github.lee.jel.domain.ItemDetail
import io.github.lee.jel.domain.Page
import io.github.lee.jel.domain.Response
import io.github.lee.jel.repository.query.QueryFilter
import io.github.lee.jel.repository.query.QueryImageTypes
import io.github.lee.jel.repository.query.QueryIncludeItemType
import io.github.lee.jel.repository.query.QuerySortBy
import io.github.lee.jel.repository.query.QuerySortOrder
import javax.inject.Inject

class ItemRepository @Inject constructor() : BaseRepository() {

    suspend fun playingList(
        userId: String,
        page: Int = 1,
        limit: Int? = 10,
        enableImageTypes: List<QueryImageTypes>? = null,
        searchTerm: String? = null,
        fields: List<String>? = null,
        mediaTypes: List<String>? = null,
    ): Response<Page<Item>> {
        val startIndex = (page - 1) * (limit ?: 10)
        val sb = StringBuilder()
        enableImageTypes?.forEachIndexed { index, item ->
            sb.append(item.toString())
            if (index != enableImageTypes.size - 1) {
                sb.append(",")
            }
        }
        return ApiModule.itemApi()
            .playingList(userId, startIndex, limit, sb.toString(), searchTerm, fields, mediaTypes)
    }

    suspend fun latest(
        userId: String,
        parentId: String?,
        page: Int = 1,
        limit: Int? = 10,
        enableImageTypes: List<QueryImageTypes>? = null,
    ): Response<List<Item>> {
        val startIndex = (page - 1) * (limit ?: 10)
        val sb = StringBuilder()
        enableImageTypes?.forEachIndexed { index, item ->
            sb.append(item.toString())
            if (index != enableImageTypes.size - 1) {
                sb.append(",")
            }
        }
        return ApiModule.itemApi()
            .latest(userId, parentId ?: "", startIndex, limit, sb.toString())
    }


    suspend fun userItems(
        userId: String?, parentId: String?,
        page: Int? = 1, size: Int? = 10,
        includeItemTypes: List<QueryIncludeItemType>? = null,
        filters: List<QueryFilter>? = null,
        sortBy: List<QuerySortBy>? = null,
        sortOrder: QuerySortOrder? = QuerySortOrder.Ascending
    ): Response<Page<Item>> {
        val startIndex = ((page ?: 1) - 1) * (size ?: 10)
        val f = filters?.map {
            it.toString()
        }
        val sb = sortBy?.map { it.toString() }
        val itemType = includeItemTypes?.map { it.toString() }
        return ApiModule.itemApi().userItems(
            userId ?: "", parentId ?: "",
            startIndex, size ?: 10,
            includeItemTypes = itemType,
            filters = f, sortBy = sb, sortOrder = sortOrder?.toString()
        )
    }

    suspend fun itemDetail(
        userId: String?, itemId: String?
    ):Response<ItemDetail> = ApiModule.itemApi().itemDetail(userId ?: "", itemId ?: "")
}